package com.crazymakercircle.ReactorModel;

import com.crazymakercircle.NioDemoConfig;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 反应器
 * 1.创建一个socketChanel连接，selector监听accept事件，设置处理事件的acceptHandle
 * 2.循环体-阻塞获取selector监听事件，交给绑定的handle处理
 *  (第一次：Handle获取到channel，创建IOHandle，IOHandle拿到acceptSocketChannel，重新注册selector，重新监听read事件，设置处理事件的IOHandle
 *  之后一直执行这两步
 *  [
 *      第二次：IOHandle从acceptSocketChannel读取数据，重新设置监听write事件
 *      第三次：IOHandle向acceptSocketChannel写入数据，重新设置监听read事件
 *  ]
 *  )
 *
 */
class EchoServerReactor implements Runnable {
    Selector selector;
    ServerSocketChannel serverSocket;

    EchoServerReactor() throws IOException {
        //Reactor初始化
        selector = Selector.open();
        serverSocket = ServerSocketChannel.open();

        InetSocketAddress address = new InetSocketAddress(NioDemoConfig.SOCKET_SERVER_IP, NioDemoConfig.SOCKET_SERVER_PORT);
        serverSocket.socket().bind(address);
        //非阻塞
        serverSocket.configureBlocking(false);

        //分步处理,第一步,接收accept事件
        SelectionKey sk = serverSocket.register(selector, SelectionKey.OP_ACCEPT);
        //attach callback object, AcceptorHandler
        sk.attach(new AcceptorHandler());
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                // 阻塞调用，一直到至少有一个通道发生了注册的IO事件。
                selector.select();
                Set<SelectionKey> selected = selector.selectedKeys();
                Iterator<SelectionKey> it = selected.iterator();
                while (it.hasNext()) {
                    //Reactor负责dispatch收到的事件
                    SelectionKey sk = it.next();
                    dispatch(sk);
                }
                selected.clear();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    void dispatch(SelectionKey sk) {
        Runnable handler = (Runnable) sk.attachment();
        //调用之前attach绑定到选择键的handler处理器对象
        if (handler != null) {
            handler.run();
        }
    }

    // Handler:新连接处理器
    class AcceptorHandler implements Runnable {
        @Override
        public void run() {
            try {
                // 获取分发的连接
                SocketChannel channel = serverSocket.accept();
                if (channel != null) {
                    // 使用同一个selector继续监听当前连接后续状态 连接->读写
                    new EchoHandler(selector, channel);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) throws IOException {
        new Thread(new EchoServerReactor()).start();
    }
}
